﻿using System.Web.Http;
using System.Web.Http.Cors;
using Newtonsoft.Json.Converters;
using TDF.Core.Configuration;
using TDF.Web.Attributes.WebApi;

namespace ARchGL.Declaration.Platform.Web
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API 配置和服务

            // Web API 路由
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
            config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new IsoDateTimeConverter()
            {
                DateTimeFormat = "yyyy-MM-dd HH:mm:ss"
            });
            GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
            config.Filters.Add(new HandlerApiErrorAttribute());
            #region 跨域
            var origins = Configs.Instance.GetValue("Cors.Origins");
            var headers = Configs.Instance.GetValue("Cors.Headers");
            var methods = Configs.Instance.GetValue("Cors.Methods");
            origins = string.IsNullOrEmpty(origins) ? "*" : origins;
            headers = string.IsNullOrEmpty(headers) ? "*" : headers;
            methods = string.IsNullOrEmpty(methods) ? "*" : methods;
            var globalCors = new EnableCorsAttribute(origins, headers, methods);
            config.EnableCors(globalCors);
            #endregion
        }
    }
}
